﻿/*----------------------------------------------------------------
           // Copyright (C) 2008 安华顺通(北京)科技有限公司
           // 版权所有。 
           //
           // 文件名：Util.cs
           // 文件功能描述：工具类。
           //
           // 
           // 创建标识：杨波
           //
           // 修改标识：
           // 修改描述：
           //
           // 修改标识：
           // 修改描述：
//----------------------------------------------------------------*/

#region UsingStatements

using System;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using log4net;
using RuleCode.WinFormsUI.Docking;
using Ionic.Zip;
using System.Text;
using System.Collections.Generic;
using EnvDTE;
using System.Reflection;
using System.Collections;

#endregion

namespace RuleCode.ObjectTree
{


    public class Util
    {
        #region Add by  DingYuliang  显示方法   
 
        public static string CryKey = "{5CA30991-2B3D-4d2e-B0B1-AD7D113A0664}";

        /// <summary>
        /// 获取或设置 右键菜单 打开新窗口 显示模式
        /// </summary>
        public static  NewFormDisplayMode NewFormDisplayMode
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置右侧 属性窗口的DockPanel
        /// </summary>
        public static  DockPanel DockPanel_Property
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置中间 打开新窗口的DockPanel
        /// </summary>
        public static DockPanel DockPanel_Middle
        {
            get;
            set;
        }
                       
        /// <summary>
        /// 获取或设置 中间打开新窗体的个数
        /// </summary>
        public static int NewWindowCount
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 折叠
        /// </summary>
        public static SplitContainer SplitContainer
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 中间窗口的右键菜单，只有在UserControl下才不为空
        /// </summary>
        public static ContextMenuStrip ContextMenuStrip_MiddleWin
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 当前 中间窗口的窗体
        /// </summary>
        public static DockContent CurrentMiddleObjectTreeForm
        {
            get;
            set;
        }


        private static MDIParent mdiParent;

        /// <summary>
        /// 获取或设置 MdiParent
        /// </summary>
        public static MDIParent MdiParent
        {
            set { mdiParent = value; }
            get { return mdiParent; }
        }

        /// <summary>
        /// 获取或设置 OTControl
        /// </summary>
        public static OTControl OTControl
        {
            get;
            set;
        }

        /// <summary>
        /// 设置 状态信息
        /// </summary>
        public static void SetStatusInfo(string infoMsg)
        {
            if (Util.NewFormDisplayMode == NewFormDisplayMode.MDIParent)
            {
                if (Util.MdiParent != null &&　Util.MdiParent.toolStripStatusLabel1!=null)
                {
                    Util.MdiParent.toolStripStatusLabel1.Text = infoMsg;   
                }
            }
            else if (Util.NewFormDisplayMode == NewFormDisplayMode.UserControl)
            {
                if (Util.OTControl != null && Util.OTControl.AddIn_ApplicationObject != null)
                {
                    Util.OTControl.AddIn_ApplicationObject.StatusBar.Text = infoMsg;
                }
            }
        }
        #endregion

        #region 唯一ID号
        /// <summary>
        /// GetNewRecId,zhouyujie
        /// </summary>
        public static Int64 GetNewRecId
        {
            get
            {
                SqlDataReader reader = SqlHelper.Instance.ExecuteReader("exec dbo.GetRecId");
                while (reader.Read())
                {
                    Int64 ret = (Int64)reader[0];
                    reader.Close();
                    return ret;
                }
                reader.Close();
                return 0;
            }
        }

        /// <summary>
        /// 获取对象树用节点ID
        /// </summary>
        public static Int64 GetNewAOTID
        {
            get 
            {
                SqlDataReader reader = SqlHelper.Instance.ExecuteReader("exec dbo.GetRecId 1");
                while (reader.Read())
                {
                    Int64 ret = (Int64)reader[0];
                    reader.Close();
                    return ret;
                }
                reader.Close();
                return 0;
            }
        }

        /// <summary>
        /// 获取Label用编码ID
        /// </summary>
        public static Int64 GetNewLabelID
        {
            get 
            {
                SqlDataReader reader = SqlHelper.Instance.ExecuteReader("exec dbo.GetRecId 2");
                while (reader.Read())
                {
                    Int64 ret = (Int64)reader[0];
                    reader.Close();
                    return ret;
                }
                reader.Close();
                return 0;
            }
        }
        #endregion

        #region 检查配置相关
       

        /// <summary>
        /// 在新建数据库的时候执行数据库所需要的信息的脚本
        /// </summary>
        public  static void ExecNewDataBaseScript(string sqlConnectStr,bool hasTables)
        {
            string sqlFileName = hasTables ? GlobalStaticDirectoryPath.SQL_HasTableFileName : GlobalStaticDirectoryPath.SQLFileName;
            string sqlScriptFilePath = Path.Combine(Util_DTE.AddIn_SetUpPath, "Data\\" + sqlFileName);
            ExecuteSqlFile(sqlConnectStr, sqlScriptFilePath);
            //if (File.Exists(sqlScriptFilePath))
            //{
            //    try
            //    {
            //        StreamReader sReader = new StreamReader(sqlScriptFilePath); 
            //        string allSqlCript = sReader.ReadToEnd();
            //        sReader.Close();

            //        allSqlCript = allSqlCript.Replace("\r\n", " ");        
            //        SqlHelper.ExecSqlScript(sqlConnectStr, allSqlCript);
            //    }
            //    catch (Exception error)
            //    {
            //        Util.SetStatusInfo(error.Message);
            //    }
            //}
        }

        /// <summary> 
        /// 执行Sql文件 
        /// </summary> 
        /// <param name="varFileName"></param> 
        /// <returns></returns> 
        public static bool ExecuteSqlFile(string sqlConnectStr,string varFileName)
        {
            if (!File.Exists(varFileName))
            {
                return false;
            }

            StreamReader sr = File.OpenText(varFileName);
            string varLine = "";
            string alSql =  "";

            while (sr.Peek() > -1)
            {
                varLine = sr.ReadLine();
                if (varLine == "")
                {
                    continue;
                }
                if (varLine.Trim().ToLower() == "go")
                {
                    SqlHelper.ExecSqlScript(sqlConnectStr, alSql);
                    alSql = "";
                }
                else
                {
                    alSql += varLine+" ";
                }
            }

            sr.Close();
            return true;
        } 




        /// <summary>
        /// 执行文件中的SQL脚本语句
        /// </summary>
        /// <param name="sqlScriptFileName"></param>
        public static void InitDataBase(string sqlScriptFileName)
        {
            string sqlScriptText = string.Empty;
            try
            {
                StreamReader sReader = new StreamReader(sqlScriptFileName);
                sqlScriptText = sReader.ReadToEnd();
                sReader.Close();
            }
            catch { }
            if (sqlScriptText != string.Empty)
                SqlHelper.Instance.ExecuteNonQuery(System.Data.CommandType.Text, sqlScriptText);
        }


        /// <summary>
        /// 检查数据库配置是否正确，数据库中的存储过程，主要表结构，等等设置
        /// </summary>
        /// <returns></returns>
        public static  void ValidateDataBaseConfig()
        {                         
            List<string> allCmdTexts = new List<string>();

            //判断是否存在RECID表以及字段:RECID,AOTID,Label;以及相应的存储过程
            bool recidExist = SqlHelper.Instance.ExistTable("RECID");
            if (!recidExist)
            {
                string cmdText = "Create Table [RECID] ([RECID bigint,AOTID bigint,Label bigint]) ON [Primary]";
                allCmdTexts.Add(cmdText);         
            }

            bool getRecidExist = SqlHelper.Instance.ExistProc("GETRECID");
            if (!getRecidExist)
            {
                string  cmdText = "";
                allCmdTexts.Add(cmdText);
            }


            foreach (string cmdText in allCmdTexts)
            {
                SqlHelper.Instance.ExecuteNonQuery(System.Data.CommandType.Text, cmdText);
            }
        }

        /// <summary>
        /// 检查 文件系统的配置是否正确，查看是否存在必要的文件，以及相关路径的设置
        /// </summary>
        /// <returns></returns>
        public static bool ValidateFileConfig()
        {
            bool result = true;
            return result;
        }
        #endregion

        #region 拷贝Templates和LabelFile 一般用于新建配置的时候用
        /// <summary>
        /// 创建一个新的配置，并且把相应的模板文件和LabelFile文件拷贝到目录下面
        /// </summary>
        /// <param name="configName"></param>
        public static void CreateNewConfig(string configName)
        { 
            if (!String.IsNullOrEmpty(configName) &&　!String.IsNullOrEmpty (Util_DTE.AddIn_SetUpPath ))
            {
                string aotPaths = Path.Combine(GetUserDataPath (),GlobalStaticDirectoryPath .AOTSProfilePath.Trim ("\\".ToCharArray ()) );
                string configPath = Path.Combine(aotPaths, configName);
                if (Directory.Exists(configPath))
                {
                    MessageBox.Show("对不起，已经存在同名的配置："+configName +"，请修改后在创建配置信息！");
                    return;
                }

                Directory.CreateDirectory(configPath);
                string devPath = Path.Combine(configPath, DevArea);
                Directory.CreateDirectory(devPath);

                string addInDataSetupPath = Path.Combine(Util_DTE.AddIn_SetUpPath, "Data");
                string templatesZipFileName = Path.Combine(addInDataSetupPath, "Templates.zip");
                using (ZipFile geneTemplateZip = ZipFile.Read(templatesZipFileName))
                {
                    foreach (ZipEntry entry in geneTemplateZip)
                        entry.Extract(devPath, ExtractExistingFileAction.OverwriteSilently);
                }
                string labelFileZipFileName = Path.Combine(addInDataSetupPath, "LabelFile.zip");
                using (ZipFile labelFileZip = ZipFile.Read(labelFileZipFileName))
                {
                    foreach (ZipEntry entry in labelFileZip)
                        entry.Extract(devPath, ExtractExistingFileAction.OverwriteSilently);
                }

            }
        }
        #endregion

        //开发与公司环境选择
        private static string devArea;

        public static string DevArea
        {
            //get { return devArea; }
            //set { devArea = value; }
            //Modify by DingYuLiang
            get {
                if (String.IsNullOrEmpty(devArea))
                    devArea = "DAT";
                return devArea;
            }
            set
            {
                devArea = value;
            }
        }

        private static SysPropertyGrid propertyGrid;

        public static SysPropertyGrid PropertyGrid             
        {
            set { propertyGrid = value; }
            get { return propertyGrid; }
        }

        private static BaseProperty preProperty;

        public static BaseProperty PreProperty
        {
            set { preProperty = value; }
            get { return preProperty; }
        }

        private static BaseProperty currentProperty;

        public static BaseProperty CurrentProperty
        {
            set { currentProperty = value; }
            get { return currentProperty; }
        }

        private static bool setPropertyInSilent;

        public static bool SetPropertyInSilent
        {
            set { setPropertyInSilent = value; }
            get { return setPropertyInSilent; }
        }
        public static void SetAllPropery(SysTreeNode node)
        {
            node.ExpandAll();
            if (node.Nodes.Count > 0)
            {
                foreach (SysTreeNode no in node.Nodes)
                {
                    SetProerptyInSilent(no);
                    SetAllPropery(no);

                }
            }
        }
        public static void SetPropertyContent(BaseProperty property)
        {
            //将上一属性序列化，再显示下一属性
            if (PreProperty != null)
                PreProperty.SerializeToXML();


            if (IsShowProperty && (!SetPropertyInSilent))
            {
                PropertyWindow.TabText = SelectedNode.Text;
                PropertyGrid.SelectedObject = property;

            }
            CurrentProperty = property;
            PreProperty = property;
        }
        /// <summary>
        /// 获取程序安装后的路径
        /// </summary>
        public static string ApplicationPath
        {
            get 
            {
                return OTPath;
            }
        }
        public static void SetPropertyContent(SysTreeNode sysTreeNode)
        {
            //读取属性内容文件流
            FileInfo fi =
                new FileInfo(GetObjDataPath + "\\" + sysTreeNode.SysXmlNode.Attributes.GetNamedItem("ID").Value + ".xml");
            if (!fi.Exists)
            {
                PropertyGrid.SelectedObject = null;
                PropertyWindow.TabText = sysTreeNode.Text;
                return;
            }
            PropertyWindow.TabText = "Property";
            //FileStream fs = new FileStream(Util.GetObjDataPath + "\\" + sysTreeNode.SysXmlNode.Attributes.GetNamedItem("ID").Value + ".xml", FileMode.Open, FileAccess.ReadWrite);
            FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite);
            //FileStream writer = new FileStream(dir + "\\" + this.ID + ".xml", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

            //DataContractSerializer ser = SysDataContractSerializer.getObject(((XmlNode)sysTreeNode.Tag).Attributes.GetNamedItem("Type").Value, fs);
            BaseProperty property =
                SysDataContractSerializer.getObject(sysTreeNode.SysXmlNode.Attributes.GetNamedItem("Type").Value, fs);
            sysTreeNode.Property = property;
            fs.Close();
            SetPropertyContent(property);
        }

        public static XmlNode changeXmlNodeName(XmlNode xmlnode, string newName)
        {
            XmlNode parent = xmlnode.ParentNode;
            if (parent != null)
            {
            }
            else
            {
                parent = SysXmlDocument.SelectSingleNode(getTreeNodeXPathQueryString()).ParentNode;
            }
            XmlElement newNode = xmlnode.OwnerDocument.CreateElement(newName);
            newNode.SetAttribute("ID", xmlnode.Attributes.GetNamedItem("ID").Value);
            newNode.SetAttribute("Type", xmlnode.Attributes.GetNamedItem("Type").Value);
            XmlNodeList list = xmlnode.ChildNodes;

            while (list.Count != 0)
            {
                newNode.AppendChild(list.Item(0));
            }
            parent.ReplaceChild(newNode, xmlnode);

            TreeViewOpr.saveOTXML();
            return newNode;
        }

        #region 文件路径

        private static string _GetLabelFilePath = null;

        /// <summary>
        /// 获取LabelFile路径 包含"\\"
        /// </summary>
        public static string GetLabelFilePath
        {
            get
            {
                if (String.IsNullOrEmpty(_GetLabelFilePath))
                    InitCurrentProfileName();
                if (String.IsNullOrEmpty(_GetLabelFilePath))
                    _GetLabelFilePath = Path.Combine (Util.OTPath ,"LabelFile");
                return _GetLabelFilePath;
            }      
        }
                                  
        public static string _GetObjDataPath = string.Empty;
        /// <summary>
        /// 属性文件路径，本地用于开发，远程用于发布。
        /// </summary>
        public static string GetObjDataPath
        {
            get
            {
                if (String.IsNullOrEmpty(_GetObjDataPath))
                    InitCurrentProfileName();
                if(String.IsNullOrEmpty (_GetObjDataPath ))
                    _GetObjDataPath = OTPath+GlobalStaticDirectoryPath.ObjectData;
                return _GetObjDataPath;
            }
        }

        /// <summary>
        /// 属性Class文件路径，本地用于开发，远程用于发布。
        /// </summary>
        public static string GetClassPath
        {
            get
            {
                string classPath = OTPath_Module +"\\"+ GlobalStaticDirectoryPath.Classes;// OTPath + GlobalStaticDirectoryPath.ModuleClasses;
                DirectoryInfo directoryInfo = new DirectoryInfo(classPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return classPath;
            }
        }
        public static void MakeSureDirectoryExistance(string path)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }
        }
        public static string GetEnumsPath
        {
            get
            {
                string enumsPath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.Enums ;// OTPath + GlobalStaticDirectoryPath.ModuleEnums;
                DirectoryInfo directoryInfo = new DirectoryInfo(enumsPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return enumsPath;
            }
        }
        public static string GetExtendDateTypesPath
        {
            get
            {
                string extendDataTypePath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.ExtendDataTypes ;// OTPath + GlobalStaticDirectoryPath.ModuleExtendDataTypes;
                DirectoryInfo directoryInfo = new DirectoryInfo(extendDataTypePath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return extendDataTypePath;
            }
        }
        public static string GetFormsPath
        {
            get
            {
                string formsPath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.Forms ;// OTPath + GlobalStaticDirectoryPath.ModuleForms;
                DirectoryInfo directoryInfo = new DirectoryInfo(formsPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return formsPath;
            }
        }
        public static string GetQueriesPath
        {
            get
            {
                string queriesPath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.Queries ;// OTPath + GlobalStaticDirectoryPath.ModuleQueries;
                DirectoryInfo directoryInfo = new DirectoryInfo(queriesPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return queriesPath;
            }
        }
        public static string GetTablesPath
        {
            get
            {
                string formsPath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.Tables ;// OTPath + GlobalStaticDirectoryPath.ModuleTables;
                DirectoryInfo directoryInfo = new DirectoryInfo(formsPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return formsPath;
            }
        }
        public static string GetPartialTablesPath
        {
            get
            {
                string formsPath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.PartialTables;// OTPath + GlobalStaticDirectoryPath.ModuleTables;
                DirectoryInfo directoryInfo = new DirectoryInfo(formsPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return formsPath;
            }
        }
        public static string GetTableFieldsPath
        {
            get
            {
                string formsPath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.TableFields ;// OTPath + GlobalStaticDirectoryPath.ModuleTableFields;
                DirectoryInfo directoryInfo = new DirectoryInfo(formsPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return formsPath;
            }
        }
        public static string GetWebFormsPath
        {
            get
            {
                string formsPath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.WebForms ;// OTPath + GlobalStaticDirectoryPath.ModuleWebForms;
                DirectoryInfo directoryInfo = new DirectoryInfo(formsPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return formsPath;
            }
        }
        public static string GetWebFormDialogsPath
        {
            get
            {
                string formsPath = OTPath_Module + "\\" + GlobalStaticDirectoryPath.WebFormDialogs ;// OTPath + GlobalStaticDirectoryPath.ModuleWebFormDialogs;
                DirectoryInfo directoryInfo = new DirectoryInfo(formsPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                return formsPath;
            }
        }
        public static string GetOutputTablePath()
        {
            string ret = OTPath_Module + "\\" + GlobalStaticDirectoryPath.Tables +"\\";// Util.OTPath + "\\Module\\Tables\\";
            DirectoryInfo directoryInfo = new DirectoryInfo(ret);
            if (!directoryInfo.Exists)
            {

                directoryInfo.Create();
            }
            return ret;
        }
        public static string GetOutputQueryPath()
        {
            string ret = OTPath_Module + "\\" + GlobalStaticDirectoryPath.Queries+"\\" ;// Util.OTPath + "\\Module\\Queries\\";
            DirectoryInfo directoryInfo = new DirectoryInfo(ret);
            if (!directoryInfo.Exists)
            {

                directoryInfo.Create();
            }
            return ret;
        }
        public static string GetOutputWebFormPath()
        {
            string ret = OTPath_Module + "\\" + GlobalStaticDirectoryPath.WebForms+"\\" ;// Util.OTPath + "\\Module\\WebForms\\";
            DirectoryInfo directoryInfo = new DirectoryInfo(ret);
            if (!directoryInfo.Exists)
            {

                directoryInfo.Create();
            }
            return ret;
        }
        public static string RootFormNameSpace
        {
            get;
            set;
        }
        public static string RootWebFormNameSpace
        {
            get;
            set;
        }
        public static string RootClassNameSpace
        {
            get;
            set;
        }
        #region WebForm template and output section
        /// <summary>
        /// 模板的根路径
        /// </summary>
        public static string TemplatesBasePath
        {
            get
            {
                return ApplicationPath + GlobalStaticDirectoryPath.Templates;
            }
        }
        public static string WebTemplatesBasePath
        {
            get
            {
                return TemplatesBasePath + GlobalStaticDirectoryPath.WebTemplates;
            }
        }

        public static string WebFormSingleTemplatePath
        {
            get
            {
                return WebTemplatesBasePath + OT.WebFormSingle;
            }

        }
        public static string WebFormMasterSlaveTemplatePath
        {
            get
            {
                return WebTemplatesBasePath + OT.WebFormMasterSlave;
            }
        }
        public static string WebFormTreeTemplatePath
        {
            get
            {
                return WebTemplatesBasePath + OT.WebFormTree;
            }
        }
        public static string WebFormParameterTemplatePath
        {
            get
            {
                return WebTemplatesBasePath + OT.WebFormParameter;
            }
        }
        public static string WebFormBlankTemplatePath
        {
            get
            {
                return WebTemplatesBasePath + OT.WebFormBlank;
            }
        }
        public static string WebFormParaByUserTemplatePath
        {
            get
            {
                return WebTemplatesBasePath + OT.WebFormParaByUser;

            }
        }
        public static string WebFormRelationTemplatePath
        {
            get
            {
                return WebTemplatesBasePath + OT.WebFormRelation;
            }
        }
        public static string WebFormOutputBasePath
        {
            get
            {
                return OTPath_Module+"\\"+GlobalStaticDirectoryPath.WebForms+"\\";
            }
        }

        public static string WebFormSingleOutputPath
        {
            get
            {
                string ret = WebFormOutputBasePath + OT.WebFormSingle;
                DirectoryInfo directoryInfo = new DirectoryInfo(ret);
                if (!directoryInfo.Exists)
                {

                    directoryInfo.Create();
                }
                return ret;
            }
        }
        public static string WebFormMasterSlaveOutputPath
        {
            get
            {
                string ret = WebFormOutputBasePath + OT.WebFormMasterSlave;
                DirectoryInfo directoryInfo = new DirectoryInfo(ret);
                if (!directoryInfo.Exists)
                {

                    directoryInfo.Create();
                }
                return ret;
            }
        }
        public static string WebFormTreeOutputPath
        {
            get
            {
                string ret = WebFormOutputBasePath + OT.WebFormTree;
                DirectoryInfo directoryInfo = new DirectoryInfo(ret);
                if (!directoryInfo.Exists)
                {

                    directoryInfo.Create();
                }
                return ret;
            }
        }
        public static string WebFormParameterOutputPath
        {
            get
            {
                string ret = WebFormOutputBasePath + OT.WebFormParameter;
                DirectoryInfo directoryInfo = new DirectoryInfo(ret);
                if (!directoryInfo.Exists)
                {

                    directoryInfo.Create();
                }
                return ret;
            }
        }
        public static string WebFormBlankOutputPath
        {
            get
            {
                string ret = WebFormOutputBasePath + OT.WebFormBlank;
                DirectoryInfo directoryInfo = new DirectoryInfo(ret);
                if (!directoryInfo.Exists)
                {

                    directoryInfo.Create();
                }
                return ret;
            }
        }
        public static string WebFormParaByUserOutputPath
        {
            get
            {
                string ret = WebFormOutputBasePath + OT.WebFormParaByUser;
                DirectoryInfo directoryInfo = new DirectoryInfo(ret);
                if (!directoryInfo.Exists)
                {

                    directoryInfo.Create();
                }
                return ret;
            }
        }
        public static string WebFormRelationOutputPath
        {
            get
            {
                string ret = WebFormOutputBasePath + OT.WebFormRelation;
                DirectoryInfo directoryInfo = new DirectoryInfo(ret);
                if (!directoryInfo.Exists)
                {

                    directoryInfo.Create();
                }
                return ret;
            }
        }
        #endregion
        public static string GetOutputWebDialogFormPath()
        {

            string ret = OTPath_Module + "\\" + GlobalStaticDirectoryPath.WebFormDialogs +"\\";// Util.GetOutputWebFormPath() + "Dialogs\\";
            DirectoryInfo directoryInfo = new DirectoryInfo(ret);
            if (!directoryInfo.Exists)
            {

                directoryInfo.Create();
            }
            return ret;
        }
        public static string GetLibPath
        {
            get
            {
                string libPath = OTPath + GlobalStaticDirectoryPath.Library;
                DirectoryInfo directoryInfo = new DirectoryInfo(libPath);
                if (!directoryInfo.Exists)
                {

                    directoryInfo.Create();
                }
                return libPath;
            }
        }

        private static string _OTPath;
        /// <summary>
        /// 运行文件路径，本地用于开发，远程用于发布。
        /// 利用DEBUG定义区别
        /// 现在主要用于 保存对象树的节点信息的文件的基本路径
        /// </summary>
        public static string OTPath
        {
            get
            {
                if (String.IsNullOrEmpty(_OTPath))
                {
                    InitOTPath();
                }
                return _OTPath ;//= GetUserDataPath() + GlobalStaticDirectoryPath.AOTSProfilePath + "\\" + GetCurrentProfileName() + "\\" + DevArea; ;
                //return ApplicationBasePath + DevArea;
            }
        }

        private static string _OTPath_Module;
        /// <summary>
        /// 获取或设置 生成 Table,TableField等类结构的文件的基本路径
        /// </summary>
        public static string OTPath_Module
        {
            get {
                if (String.IsNullOrEmpty(_OTPath_Module))
                {
                    InitOTPath();
                }                     
                return _OTPath_Module;
            }
        }

        /// <summary>
        /// 初始化 OTPath 和OTPath_Module
        /// </summary>
        public static void InitOTPath()
        {                                           
            //XmlDocument configFile = new XmlDocument();
            //configFile.Load(Util.GetConfigFilePath());
            //XmlNode currentprofilesname = configFile.SelectSingleNode("//currentprofilename");

            string cur_name = GetCurrentProfileName() ;
            _OTPath = GetProfileValue(cur_name, "OTPath");
            _OTPath_Module = GetProfileValue(cur_name, "OTPath_Module");
            _OTPath = _OTPath.Trim().TrimEnd("\\".ToCharArray());
            _OTPath_Module = _OTPath_Module.Trim().TrimEnd("\\".ToCharArray());

            if (String.IsNullOrEmpty ( _OTPath) )    
                _OTPath = GetUserDataPath() + GlobalStaticDirectoryPath.AOTSProfilePath + "\\" + cur_name + "\\" + DevArea;
            if (String.IsNullOrEmpty(_OTPath_Module))
                _OTPath_Module = _OTPath.TrimEnd("\\".ToCharArray ()) + GlobalStaticDirectoryPath .ModulePath.TrimEnd("\\".ToCharArray ()) ;
            if (!Directory.Exists(_OTPath))
                Directory.CreateDirectory(_OTPath);
            if (!Directory.Exists(_OTPath_Module))
                Directory.CreateDirectory(_OTPath_Module);
            
        }

        private static string applicationBasePath;
        public static string ApplicationBasePath
        {
            get
            {
                //#if DEBUG
                //                return @"D:\work\ObjectTree\RuleCode.Application\bin\Debug";
                //                //return Path.GetDirectoryName(Application.ExecutablePath);
                //#endif


                //todo:current aot path
                if(applicationBasePath==null)
                {
                     XmlDocument configFile = new XmlDocument();
                     configFile.Load(Util.GetConfigFilePath());  
                     XmlNode currentprofilesname = configFile.SelectSingleNode("//currentprofilename");
                     string cur_name = currentprofilesname.FirstChild.Value; 
                     applicationBasePath = GetUserDataPath()+GlobalStaticDirectoryPath.AOTSProfilePath+"\\"+cur_name+"\\";                     
          
                }
                //applicationBasePath = "\\\\192.168.0.2\\VSObjectTree\\";
                return applicationBasePath;
            }

        }
        #endregion

        #region 配置XML文件和当前配置相关
        private static string _CurrentProfileName = null;
        /// <summary>
        /// 获取当前解决方案对应的配置文件的值
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentProfileName()
        {
            if (_CurrentProfileName == null)
            {
                InitCurrentProfileName();
            }
            return _CurrentProfileName;// GetConfigValue("currentprofilename");  
        }

        /// <summary>
        /// 根据连接字符串的ID获取 连接字符串
        /// </summary>
        /// <param name="cnnStrID">GUID唯一标志符</param>
        /// <returns></returns>
        public static string GetConnectString(string cnnStrID)
        {                                                            
            string cnnStr = string.Empty;
            string profileName = GetProfilePath();
            try
            {
                XmlDocument profileDoc = new XmlDocument();
                profileDoc.Load(profileName);
                XmlNode node = profileDoc.SelectSingleNode("//cnnString[@ID='" + cnnStrID + "']");
                if (node != null && node.Attributes.GetNamedItem("Value") != null)
                    cnnStr = node.Attributes.GetNamedItem("Value").Value;
            }
            catch (Exception error)
            {
                SetStatusInfo(error.Message);
            }
            return cnnStr;
        }
        /// <summary>
        /// 获取 当前的SQL链接字符串
        /// </summary>
        /// <returns></returns>
        public static string GetConnectString()
        {
            string cnnString = string.Empty;
            string curConfigName =_CurrentProfileName ;

            try
            {
                if (string.IsNullOrEmpty(_CurrentProfileName))
                    throw new Exception("您当前没有配置顺通企业级应用平台！！");


                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(GetProfilePath ());
                XmlNode aotNode = xmlDoc.SelectSingleNode("//aot[@Name='"+curConfigName +"']");
                if (aotNode != null && aotNode.Attributes .GetNamedItem ("cnnStringID")!=null)
                {
                    string cnnStrID = aotNode.Attributes.GetNamedItem("cnnStringID").Value;
                    XmlNode cnnStrNode = xmlDoc.SelectSingleNode("//cnnString[@ID='"+cnnStrID +"']");
                    if (cnnStrNode != null && cnnStrNode.Attributes.GetNamedItem("Value") != null)
                        return cnnStrNode.Attributes.GetNamedItem("Value").Value;
                }
            }
            catch(Exception error) {
                Util.SetStatusInfo(error.Message);
            }
            return cnnString;
        }

        /// <summary>
        /// 重新初始化
        /// </summary>
        public static void SetBack()
        {
            Util._OTPath = string.Empty;
            Util._OTPath_Module = string.Empty;
            Util._CurrentProfileName = string.Empty;
        }
        /// <summary>
        /// 重新初始化 CurrentProfileName
        /// 一般是重新加载 解决方案后运行
        /// </summary>
        public static void InitCurrentProfileName()
        {
            Util_DTE.AddIn_SetUpPath = GetConfigValue("setuppath").TrimEnd ("\\".ToCharArray ())+"\\";
            

            if (Util_DTE.AddIn_ApplicationObject != null && Util_DTE.AddIn_ApplicationObject.Solution.Count > 0)
            {
                Util_DTE._AllGenerateTypePathProjects = new System.Collections.Generic.Dictionary<GenerateFileType, Struct_GenerateTypePathProject>();

                XmlDocument soluConfigFile = new XmlDocument();   
                soluConfigFile.Load(Util.GetSolutionConfigPath ());                          
                string solutionName = Util_DTE.AddIn_ApplicationObject.Solution.FullName;
                XmlNode solutionsNode = soluConfigFile.SelectSingleNode("//Solutions");
                XmlNode soluNode = solutionsNode.SelectSingleNode("//solution[@Path='" + solutionName + "']");
                if (soluNode == null)
                {
                    soluNode = CreateNewSolutionNode(soluConfigFile, solutionsNode, Util_DTE.AddIn_ApplicationObject.Solution.FullName , Util_DTE.AddIn_ApplicationObject.Solution.FullName, true,false );

                    soluConfigFile.Save(Util.GetSolutionConfigPath());
                }
                       
                if (soluNode != null)
                {
                    XmlNode attr = soluNode.Attributes.GetNamedItem("ProfileName");
                    if (attr != null)
                        _CurrentProfileName = attr.Value;
                    else
                        _CurrentProfileName = string.Empty;

                    attr = soluNode.Attributes.GetNamedItem("CopyAtCompile");
                    if (attr != null)
                        Util_DTE.IsAddToProjectAtCompiled  = (attr.Value == "true") ? true : false;
                    else
                        Util_DTE.IsAddToProjectAtCompiled = true;


                    


                    //初始化 生成代码路径 在项目中的
                    GenerateFileType[] allGenerateFileType = new GenerateFileType[] {GenerateFileType.Class , GenerateFileType.Enum ,GenerateFileType.ExtendDataType ,
                        GenerateFileType.Form ,GenerateFileType.Query ,GenerateFileType.Table, GenerateFileType .TableField ,GenerateFileType .WebForm };
                    foreach(GenerateFileType _GenerateFileType in allGenerateFileType )
                    {
                        Struct_GenerateTypePathProject gStruct = new Struct_GenerateTypePathProject();
                        gStruct = Util_DTE.GetGenerateTypePathProjectStrct(soluNode, _GenerateFileType, "//solution[@Path='" + solutionName + "']");
                        Util_DTE.AllGenerateTypePathProjects.Add(_GenerateFileType, gStruct);
                    }

                    //初始化生成代码的 命名空间名称
                    XmlNode nameSpaceNode = soluNode.SelectSingleNode("//solution[@Path='" + solutionName + "']" + "//RootNameSpace");
                    XmlNode rootWebFormsName = nameSpaceNode.SelectSingleNode("//solution[@Path='" + solutionName + "']" + "//RootNameSpace" + "//WebForms");
                    if (rootWebFormsName != null && !String.IsNullOrEmpty(rootWebFormsName.InnerText))
                        Util.RootWebFormNameSpace = rootWebFormsName.InnerText.Trim();
                    else
                        Util.RootWebFormNameSpace = "ERPWebForms";

                    XmlNode rootClassName = nameSpaceNode.SelectSingleNode("//solution[@Path='" + solutionName + "']" + "//RootNameSpace" + "//Classes");
                    if (rootClassName != null && !String.IsNullOrEmpty(rootClassName.InnerText))
                        Util.RootClassNameSpace = rootClassName.InnerText.Trim();
                    else
                        Util.RootClassNameSpace = "RuleCode";


                    XmlNode rootFormName = nameSpaceNode.SelectSingleNode("//solution[@Path='" + solutionName + "']" + "//RootNameSpace" + "//Forms");
                    if (rootFormName != null && !String.IsNullOrEmpty(rootFormName.InnerText))
                        Util.RootFormNameSpace  = rootFormName.InnerText.Trim ();
                    else
                        Util.RootFormNameSpace = "RuleCode.Forms";

                    //更新数据库连接  
                    SqlHelper.UpdateSqlConnection();


                    //是否要添加到 Subversion版本库中管理
                    attr = soluNode.Attributes.GetNamedItem("AddToSubvesion");
                    if (attr != null)
                        Util_DTE.IsAddLabelAndAOTToSolution = (attr.Value == "true") ? true : false;
                    else
                        Util_DTE.IsAddLabelAndAOTToSolution = false;

                    _GetLabelFilePath =Path.Combine (Util.OTPath , "LabelFile");
                    _GetObjDataPath =OTPath+ GlobalStaticDirectoryPath.ObjectData;

                    Util_DTE.AllFileVersionStruct = null;
                    Util_DTE.AllFileVersionStruct = new Dictionary<FileVersionType, Struct_GenerateTypePathProject>();
                    Util_DTE.AllFileVersionStruct.Clear();

                    //如果是的话，就要更改LabelFile路径和AOTFile路径
                    if (Util_DTE.IsAddLabelAndAOTToSolution && soluNode !=null)
                    {
                        XmlNode labelNode = soluNode.SelectSingleNode("//solution[@Path='" + solutionName + "']" + "/paths/LabelFile");
                        if (labelNode != null && labelNode.Attributes.GetNamedItem("Project") != null &&labelNode .Attributes.GetNamedItem ("Value")!=null )
                        { 
                            string projectName = labelNode.Attributes.GetNamedItem("Project").Value ;
                            string labelPath = labelNode.Attributes.GetNamedItem("Value").Value;
                            Project project = Util_DTE.FindProject(projectName);
                            if (project != null)
                            { 
                                Struct_GenerateTypePathProject pathProject = new Struct_GenerateTypePathProject ();
                                pathProject .Project = project ;
                                pathProject.GeneratePath = labelPath;
                                Util_DTE.AllFileVersionStruct.Add(FileVersionType.LabelFile, pathProject); 
                                _GetLabelFilePath =Path.Combine ( (new FileInfo(project.FullName)).DirectoryName , labelPath.Trim ("\\".ToCharArray ())+"\\LabelFile");
                            }   
                        }

                        XmlNode AotNode = soluNode.SelectSingleNode("//solution[@Path='" + solutionName + "']" + "/paths/AOTFile");
                        if (AotNode != null && AotNode.Attributes.GetNamedItem("Project")!=null && AotNode.Attributes.GetNamedItem("Value") != null)
                        {
                            string projectName = AotNode.Attributes.GetNamedItem("Project").Value;
                            string aotpath = AotNode.Attributes.GetNamedItem("Value").Value;
                            Project project = Util_DTE.FindProject(projectName);
                            if (project != null)
                            {
                                Struct_GenerateTypePathProject pathProject = new Struct_GenerateTypePathProject();
                                pathProject.Project = project;
                                pathProject.GeneratePath = aotpath;
                                Util_DTE.AllFileVersionStruct.Add(FileVersionType.AOTFile, pathProject);

                                Util_DTE.GetAOTFileProject = project;
                                Util_DTE.GetAOTFileProjectPath = aotpath;
                                _GetObjDataPath =Path.Combine ( (new FileInfo(project.FullName)).DirectoryName, aotpath.Trim ("\\".ToCharArray ())+GlobalStaticDirectoryPath .ObjectData ) ;
                            }
                        }
                    }

                }                       
            }
        }

        public static XmlNode  CreateNewSolutionNode(XmlDocument xmlDoc,XmlNode solutionsNode,string solutionName,string path,bool CopyAtCompile,bool addToSubversion)
        {               
            XmlNode solutionNode = xmlDoc.CreateElement("solution");
            XmlAttribute attrNode = xmlDoc.CreateAttribute("Path");
            attrNode.Value = Util_DTE.AddIn_ApplicationObject.Solution.FullName;
            solutionNode.Attributes.Append(attrNode);

            attrNode = xmlDoc.CreateAttribute("ProfileName");
            attrNode.Value = string.Empty;
            solutionNode.Attributes.Append(attrNode);

            attrNode = xmlDoc.CreateAttribute("CopyAtCompile");
            attrNode.Value = CopyAtCompile ? "true":"false";
            solutionNode.Attributes.Append(attrNode);

            attrNode = xmlDoc.CreateAttribute("AddToSubvesion");
            attrNode.Value = addToSubversion  ? "true" : "false";
            solutionNode.Attributes.Append(attrNode);


            XmlNode pathNode = xmlDoc.CreateElement("paths");
            string[] allPaths = new string[] { "Tables", "Queries", "TableFields", "ExtendDataTypes", "Enums", "WebForms", "Classes", "Forms" };
            foreach (string type in allPaths)
            {
                CreateNewClassFilePathNode(xmlDoc, pathNode, type);
            } 
            solutionNode.AppendChild(pathNode);

            XmlNode rootNamespaceNode = xmlDoc.CreateElement("RootNameSpace");
            XmlNode childRootNode = xmlDoc.CreateElement("Classes");
            childRootNode.InnerText = string.Empty;
            rootNamespaceNode.AppendChild(childRootNode);

            childRootNode = xmlDoc.CreateElement("WebForms");
            childRootNode.InnerText = string.Empty;
            rootNamespaceNode.AppendChild(childRootNode);

            childRootNode = xmlDoc.CreateElement("Forms");
            childRootNode.InnerText = string.Empty;
            rootNamespaceNode.AppendChild(childRootNode);

            solutionNode.AppendChild(rootNamespaceNode);

            solutionsNode.AppendChild(solutionNode);
            return solutionNode;               
        }

        public static XmlNode CreateNewClassFilePathNode(XmlDocument xmlDoc, XmlNode pathNode,string type)
        {
            XmlNode childChildNode = xmlDoc.CreateElement(type);
            XmlAttribute childChildAttr = xmlDoc.CreateAttribute("Project");
            childChildAttr.Value = string.Empty;
            childChildNode.Attributes.Append(childChildAttr);
            childChildAttr = xmlDoc.CreateAttribute("Value");
            childChildAttr.Value = string.Empty;
            childChildNode.Attributes.Append(childChildAttr);
            pathNode.AppendChild(childChildNode);
            return pathNode;
        }

        /// <summary>
        /// 设置当前解决方案对应的配置文件
        /// </summary>
        /// <param name="profileName"></param>
        public static void SetCurrentProfileName(string profileName)
        {
            if (Util_DTE.AddIn_ApplicationObject != null && Util_DTE.AddIn_ApplicationObject.Solution.Count > 0)
            {  
                XmlDocument soluConfigFile = new XmlDocument();
                soluConfigFile.Load(Util.GetSolutionConfigPath ());
                string solutionName = Util_DTE.AddIn_ApplicationObject.Solution.FullName ;
                XmlNode solutionsNode = soluConfigFile.SelectSingleNode("//Solutions");
                XmlNode soluNode = solutionsNode.SelectSingleNode("//solution[@Path='" + solutionName + "']");
                if (soluNode != null)
                {
                    XmlNode attr = soluNode.Attributes.GetNamedItem("ProfileName");
                    if (attr != null)
                        attr.Value = profileName;
                    soluConfigFile.Save(Util.GetSolutionConfigPath());
                    _CurrentProfileName = attr.Value;
                }
            }
        }

        /// <summary>
        /// 获取程序配置值,输入配置名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetConfigValue(string name)
        {
            if(!string.IsNullOrEmpty(name))
            {
            XmlDocument configFile = new XmlDocument();
            configFile.Load(Util.GetConfigFilePath());
            XmlNode currentprofilesname = configFile.SelectSingleNode("//"+name);
            string cur_name = currentprofilesname.FirstChild.Value;
            return cur_name;
            }
            return "";
 
        }
        public static string GetProfileValue(string pro_name, string name)
        {

            if (!(string.IsNullOrEmpty(pro_name)&&string.IsNullOrEmpty(name)))
            {
                string cur_name=string.Empty;
                XmlDocument configFile = new XmlDocument();
                configFile.Load(Util.GetProfilePath());
                XmlNode select = configFile.SelectSingleNode("//aot[@Name='" + pro_name + "']");
                if (select != null)
                {
                    cur_name = select.Attributes.GetNamedItem(name).Value;
                   
                }     
               
                return cur_name;
            }
            return "";

        }
        #endregion

        private static string currentProjectPath;
        public static string  CurrentProjectRoot
        {
            get { return currentProjectPath; }
            set { currentProjectPath = value; }

    }
        public static SysTreeNode FindChild(SysTreeNode node, string chilName)
        {
            node.Expand();
            foreach (TreeNode treeNode in node.Nodes)
            {
                if (treeNode.Text.Equals(chilName))
                {
                    return (SysTreeNode)treeNode;
                }
            }
            return null;
        }

        //惟一的属性窗口
        private static InfoWindow propertyWindow;

        public static InfoWindow PropertyWindow
        {
            set { propertyWindow = value; }
            get { return propertyWindow; }
        }

        private static DockPanel docPanel;

        public static DockPanel DockPanel
        {
            set { docPanel = value; }
            get { return docPanel; }
        }
        private static string applicationName;
        public static string ApplicationName
        {
            get
            {
                return "顺通企业级应用平台"; //"SharpERP";//
            }

        }

        #region 相关配置文件的路径获取方法
        /// <summary>
        /// profiles.xml
        /// </summary>
        /// <returns></returns>
        public static string GetProfilePath()
        {
            return Util.GetUserDataPath() + GlobalStaticDirectoryPath.ProfilePath;
        }

        /// <summary>
        /// config.xml
        /// </summary>
        /// <returns></returns>
        public static string GetConfigFilePath()
        { return Util.GetUserDataPath() + GlobalStaticDirectoryPath.ConfigFilePath; }
        static public string GetUserDataPath()
        {
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            dir = System.IO.Path.Combine(dir, ApplicationName);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            return dir;
        }

        /// <summary>
        /// 获取 Solutions和配置文件一一对应关系的xml文件;solutions.xml
        /// </summary>
        /// <returns></returns>
        public static string GetSolutionConfigPath()
        {
            return Util.GetUserDataPath() + GlobalStaticDirectoryPath.SolutionConfigPath;
        }
        #endregion

        #region 对象树方法

        private static SysTreeNode selectedNode;

        public static SysTreeNode SelectedNode
        {
            set { selectedNode = value; }
            get { return selectedNode; }
        }

        public static void setPropertyWindow(Object obj)
        {                                     
            propertyWindow.ObjectInProp = obj;
            IsShowProperty = true;
            if (Util.NewFormDisplayMode == NewFormDisplayMode.MDIParent)
            {
                propertyWindow.Show(DockPanel);
                propertyWindow.MainSplitContainer.Panel1Collapsed = true ; 
            }
            else if (Util.NewFormDisplayMode == NewFormDisplayMode.UserControl && Util.DockPanel_Property != null)
            {
                propertyWindow.MainSplitContainer.Panel1Collapsed = true ;
                propertyWindow.MainSplitContainer.Panel1MinSize = 25;
                propertyWindow.MainSplitContainer.FixedPanel = FixedPanel.Panel1 ;
                propertyWindow.Show(Util.DockPanel_Property, DockState.Document);
            }
        }   

        private static bool isShowProperty;

        public static bool IsShowProperty
        {
            set { isShowProperty = value; }
            get { return isShowProperty; }
        }

        private static XmlDocument sysXmlDocument;

        public static XmlDocument SysXmlDocument
        {
            set { sysXmlDocument = value; }
            get { return sysXmlDocument; }
        }

        private static SysTreeView parentTreeView;

        public static SysTreeView ParentTreeView
        {
            set { parentTreeView = value; }
            get { return parentTreeView; }
        }

        private static SysTreeView activeTreeView;

        public static SysTreeView ActiveTreeView
        {
            set { activeTreeView = value; }
            get { return activeTreeView; }
        }

        public static XmlNode getAddingParentNode()
        {
            return sysXmlDocument.SelectSingleNode(getTreeNodeXPathQueryString());
        }

        public static string getTreeNodeXPathQueryString()
        {
            //(Util.ActiveTreeView.BaseNodePath + Util.SelectedNode.FullPath).Replace("\\", "/");
            //return (ActiveTreeView.BaseNodePath + selectedNode.FullPath).Replace("\\", "/");
            return ActiveTreeView.BaseNodePath + OT.XPathRootSeperator + selectedNode.FullPath;
        }

        public static string getMaxTypeID(XmlNode node)
        {
            string ID = GetNewAOTID.ToString();
            node.Attributes.Item(0).Value = ID;
            return ID;
            //string ID =
            //    TreeViewOpr.typeMaxNum.SelectSingleNode("//" + node.Attributes["Type"].Value).Attributes["ID"].Value;
            //node.Attributes.Item(0).Value = ID;
            //int idint = Convert.ToInt32(ID);
            //idint++;
            //TreeViewOpr.typeMaxNum.SelectSingleNode("//" + node.Attributes["Type"].Value).Attributes.Item(0).Value =
            //    Convert.ToString(idint);
            //return ID;
        }

        //返回新建结点的初始名称，方法为遍历兄弟结点，查找初始前缀的个数，返回初始前缀+相同前缀+1
        /*public static string getInitName(SysTreeNode parent, string initPrefix)
        {
            int count = 1;
            //填入要比较的种子。
            string maxName = parent.FirstNode.Text;
            string maxNumName = null;
            string name;

            // parent.nodecount==0
            if (parent.GetNodeCount(false) == 1)
            {
                name = initPrefix + "1";
            }
            else
            {
                //bool refrain = false;
                foreach (SysTreeNode node in parent.Nodes)
                {
                    if (node.Text.StartsWith(initPrefix))
                    {
                        count++;
                        if (maxName.Length < node.Text.Length)
                        {
                            maxName = node.Text;
                        }
                    }
                }
                maxNumName = maxName;
                foreach (SysTreeNode node in parent.Nodes)
                {
                    if (node.Text.Length == maxName.Length)
                    {
                        if (String.Compare(maxNumName, node.Text, true) < 0)
                        {
                            maxNumName = node.Text;
                        }
                    }
                }

                int len = maxNumName.Length;
                int i = Convert.ToInt32(maxNumName.Substring(len - 1));
                i++;
                string preString = maxNumName.Substring(0, len - 1);
                name = preString + i;
            }

            return name;
        }
        */

        public static string getTableFieldFormat(string type, EDTProperty property)
        {
            string ret = string.Empty;

            switch (type)
            {
                case EDTTypes.EDTTypeString:
                    {
                        if (property != null)
                        {
                            ret = "[varchar](" + ((EDTStringProperty)property).StringSize +
                                  ") COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('')";
                        }
                        else ret = "[varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('')";
                        break;
                    }
                case EDTTypes.EDTTypeInt:
                    {
                        ret = "[int] NOT NULL DEFAULT ((0))";
                        break;
                    }
                case EDTTypes.EDTTypeReal:
                    {
                        ret = "[numeric](28, 12) NOT NULL DEFAULT ((0))";
                        break;
                    }
                case EDTTypes.EDTTypeDate:
                    {
                        ret = "[datetime] NOT NULL DEFAULT ('1900-01-01 00:00:00.000')";
                        break;
                    }
                case EDTTypes.EDTTypeTime:
                    {
                        ret = "[int] NOT NULL DEFAULT ((0))";
                        break;
                    }
                case EDTTypes.EDTTypeEnum:
                    {
                        ret = "[int] NOT NULL DEFAULT ((0))";
                        break;
                    }
                case EDTTypes.EDTtypeContainer:
                    {
                        ret = "[image] NULL DEFAULT (NULL)";
                        break;
                    }
                case EDTTypes.EDTTypeInt64:
                    {
                        ret = "[bigint] NOT NULL DEFAULT ((0))";
                        break;
                    }
            }
            return ret;
        }

        //不允许重命名结点名称的正则表达式,弃用正则表达式，正则表达式采用贪心算法，以下列字符串为前缀也匹配成功。采用字符串数组在性能上也优于正则表达式。
        public const string DisallowLabelEditRegEx =
            "对象设计器|数据字典|表|Fields|FieldGroup|Indexes|Relations|DeleteActions|Methods|扩展类型|视图|枚举|宏|类|窗体|报表|查询|工作|菜单|目录项|显示|输出|动作|网络|资源|引用";

        public static string[] DisAllowLabelEditStrings = new[]
                                                             {
                                                                 "对象设计器", "数据字典", "表", "Fields", "FieldGroups", "Indexes",
                                                                 "Relations", "DeleteActions", "Methods", "扩展类型", "目录项",
                                                                 "视图", "枚举", "宏", "类", "窗体", "报表", "查询", "工作", "菜单",
                                                                 "显示",
                                                                 "输出", "动作", "网络", "资源", "引用","ArrayElements","DataSources","Designs"
                                                             };

        /// <summary>
        /// Adding a specific node.
        /// </summary>
        /// <param name="templetePath"></param>
        /// <param name="nodeType"></param>
        /// <param name="propertyType"></param>
        /// <param name="defaultName"></param>
        public static string addNode(string templetePath, string nodeType, Type propertyType, string defaultName)
        {
            //ADDNODE
            string name;
            SelectedNode.Expand();
            ActiveTreeView.BeginUpdate();
            XmlNode TemplateNode = TreeViewOpr.nodesTemplate.SelectSingleNode(templetePath);
            XmlNode parentNode = getAddingParentNode();
            XmlNode Node = TemplateNode.CloneNode(true).FirstChild;

            Node = SysXmlDocument.ImportNode(Node, true);
            parentNode.InsertAfter(Node, parentNode.FirstChild);
          
            string ID = getMaxTypeID(Node);
            if (string.IsNullOrEmpty(defaultName))
            {
                name = nodeType + ID;
            }
            else
            {
                name = defaultName;
            }

            SysTreeNode treeNode = new SysTreeNode(name)
                                       {
                                           SysXmlNode = Node,
                                           ImageKey = (Node.Attributes.GetNamedItem("Type").Value + ".ico"),
                                           SelectedImageKey = (Node.Attributes.GetNamedItem("Type").Value + ".ico")
                                       };
            SelectedNode.Nodes.Insert(0, treeNode);
            ActiveTreeView.SelectedNode = treeNode;
            treeNode.SysXmlNode = changeXmlNodeName(Node, name);
            SelectedNode = treeNode;
            AddAllSubNodes(TemplateNode.FirstChild, treeNode);

            BaseProperty property = (BaseProperty)Activator.CreateInstance(propertyType);
            if (property is NameProperty)
            {
                ((NameProperty)property).Name = name;
            }
            property.ID = ID;
            SetPropertyContent(property);
            treeNode.Property = property;
            property.SerializeToXML();
            TreeViewOpr.saveToXML();
            ActiveTreeView.EndUpdate();
            //添加完节点即进入Label编辑状态
            if (IsLabelEditAfterAddNewNode)
            {
                ActiveTreeView.SelectedNode.BeginEdit();
            }
            
            //如果是团队设置，需要版本控制，而将AOTFile加入项目
            if(Util_DTE .IsAddLabelAndAOTToSolution )
            {
                if (Util_DTE.GetAOTFileProject != null)
                {
                    string propertyFileName = Path.Combine(Util.GetObjDataPath, ID+".xml");
                    Util_DTE.AddGeneratedFileToProject(Util_DTE.GetAOTFileProject, Util_DTE.GetAOTFileProjectPath.TrimEnd("\\".ToCharArray ())+GlobalStaticDirectoryPath .ObjectData , propertyFileName);
                }
            }


            return ActiveTreeView.SelectedNode.Text;
        }

        private static void AddAllSubNodes(XmlNode TemplateNode, SysTreeNode treeNode)
        {

            //if (TemplateNode.HasChildNodes)
            //{
            //    if (TemplateNode.FirstChild.HasChildNodes)
            //    {
                    foreach (XmlNode node in TemplateNode.ChildNodes)
                    {
                        AddAllSubNodes(node, addSubNode(node, treeNode));
                    }
            //    }
            //}
        }
        /// <summary>
        /// 添加新结点后不直接进入节点标签编辑状态
        /// </summary>
        /// <param name="templetePath"></param>
        /// <param name="nodeType"></param>
        /// <param name="propertyType"></param>
        /// <param name="defaultName"></param>
        /// <param name="enableLabelEditAfterAdded"></param>
        /// <returns></returns>
        public static string addNode(string templetePath, string nodeType, Type propertyType, string defaultName, bool enableLabelEditAfterAdded)
        {
            IsLabelEditAfterAddNewNode = enableLabelEditAfterAdded;
            string ret = addNode(templetePath, nodeType, propertyType, defaultName);
            IsLabelEditAfterAddNewNode = !enableLabelEditAfterAdded;
            return ret;
        }
        
        public static string addNode(string templetePath, string nodeType, Type propertyType, string defaultName, bool enableLabelEditAfterAdded,NewNodePosition position)
        {
            IsLabelEditAfterAddNewNode = enableLabelEditAfterAdded;
            string ret = addNode(templetePath, nodeType, propertyType, defaultName,position);
            IsLabelEditAfterAddNewNode = !enableLabelEditAfterAdded;
            return ret;
        }
        public static string addNode(string templetePath, string nodeType, Type propertyType, string defaultName,NewNodePosition position)
        {
            //ADDNODE
            string name;
            SelectedNode.Expand();
            ActiveTreeView.BeginUpdate();
            XmlNode TemplateNode = TreeViewOpr.nodesTemplate.SelectSingleNode(templetePath);
            XmlNode parentNode = getAddingParentNode();
            XmlNode Node = TemplateNode.CloneNode(true).FirstChild;

            Node = SysXmlDocument.ImportNode(Node, true);
            if(position.Equals(NewNodePosition.Default))
            {
            parentNode.InsertAfter(Node, parentNode.FirstChild);
            }
            else
            {
                parentNode.InsertAfter(Node,parentNode.LastChild);
            }

            string ID = getMaxTypeID(Node);
            if (string.IsNullOrEmpty(defaultName))
            {
                name = nodeType + ID;
            }
            else
            {
                name = defaultName;
            }

            SysTreeNode treeNode = new SysTreeNode(name)
            {
                SysXmlNode = Node,
                ImageKey = (Node.Attributes.GetNamedItem("Type").Value + ".ico"),
                SelectedImageKey = (Node.Attributes.GetNamedItem("Type").Value + ".ico")
            };
            if (position.Equals(NewNodePosition.Default))
            {
                SelectedNode.Nodes.Insert(0, treeNode);
            }
            else
            {
                SelectedNode.Nodes.Insert(selectedNode.Nodes.Count, treeNode);
            }
            //SelectedNode.Nodes.Insert(0, treeNode);
            ActiveTreeView.SelectedNode = treeNode;
            treeNode.SysXmlNode = changeXmlNodeName(Node, name);
            SelectedNode = treeNode;
            AddAllSubNodes(TemplateNode.FirstChild, treeNode);

            BaseProperty property = (BaseProperty)Activator.CreateInstance(propertyType);
            if (property is NameProperty)
            {
                ((NameProperty)property).Name = name;
            }
            property.ID = ID;
            SetPropertyContent(property);
            treeNode.Property = property;
            property.SerializeToXML();
            TreeViewOpr.saveToXML();
            ActiveTreeView.EndUpdate();
            //添加完节点即进入Label编辑状态
            if (IsLabelEditAfterAddNewNode)
            {
                ActiveTreeView.SelectedNode.BeginEdit();
            }

            //如果是团队设置，需要版本控制，而将AOTFile加入项目
            if (Util_DTE.IsAddLabelAndAOTToSolution)
            {
                if (Util_DTE.GetAOTFileProject != null)
                {
                    string propertyFileName = Path.Combine(Util.GetObjDataPath, ID + ".xml");
                    Util_DTE.AddGeneratedFileToProject(Util_DTE.GetAOTFileProject, Util_DTE.GetAOTFileProjectPath.TrimEnd("\\".ToCharArray()) + GlobalStaticDirectoryPath.ObjectData, propertyFileName);
                }
            }


            return ActiveTreeView.SelectedNode.Text;
        }
        private static bool isLabelEditAfterAddNewNode = true;
        public static bool IsLabelEditAfterAddNewNode
        {
            get { return isLabelEditAfterAddNewNode; }
            set { isLabelEditAfterAddNewNode = value; }
        }

        public static void addNodeInBackGround(string name, string label, string parentNodeXPath, string templatePath, Type propertyType)
        {


            XmlNode TemplateNode = TreeViewOpr.nodesTemplate.SelectSingleNode(templatePath);
            XmlNode parentNode = sysXmlDocument.SelectSingleNode(parentNodeXPath);
            XmlNode Node = TemplateNode.CloneNode(true).FirstChild;
            Node = SysXmlDocument.ImportNode(Node, true);
            parentNode.InsertAfter(Node, parentNode.FirstChild);
            string ID = getMaxTypeID(Node);



            changeXmlNodeName(Node, name);


            BaseProperty property = (BaseProperty)Activator.CreateInstance(propertyType);
            if (property is NameProperty)
            {
                ((NameProperty)property).Name = name;
            }
            property.ID = ID;

            property.SerializeToXML();
            TreeViewOpr.saveToXML();

        }
        private static ILog logger;

        public static ILog Logger
        {
            set { logger = value; }
            get { return logger; }
        }

        private static Application app;

        public static Application App
        {
            set { app = value; }
            get { return app; }
        }

        public static SysTreeNode addSubNode(XmlNode node, SysTreeNode tableNode)
        {
            SysTreeNode treeNode = new SysTreeNode(node.Name) { SysXmlNode = node };
            tableNode.Nodes.Add(treeNode);
            treeNode. ImageKey = node.Attributes.GetNamedItem("Type").Value + ".ico";
            treeNode.SelectedImageKey = node.Attributes.GetNamedItem("Type").Value + ".ico";
            return treeNode;
        }



        public static void SetProerptyInSilent(SysTreeNode node)
        {
            SetPropertyInSilent = true;
            SetPropertyContent(node);
            SetPropertyInSilent = false;
        }

        //private static MySharp.MySharpIDE ide;

        //public static MySharp.MySharpIDE IDE
        //{
        //    set { ide = value; }
        //    get { return ide; }
        //}

        private static InfoWindows infoWindows;
        public static void Info(string _string)
        {
            if (infoWindows == null)
            {
                infoWindows = new InfoWindows();
            }
            infoWindows.Show();
            infoWindows.info(_string);
        }

        /// <summary>
        /// 解压缩LabelFile文件
        /// </summary>
        /// <param name="toLabelFilePath"></param>
        public static void UnpackLabelFiles(string toLabelFilePath)
        {
            if (!Directory.Exists(toLabelFilePath))
                Directory.CreateDirectory(toLabelFilePath);
            string sourceLabelFileZip = Util_DTE.AddIn_SetUpPath + "Data\\LabelFile.zip";
            using (ZipFile zip1 = ZipFile.Read(sourceLabelFileZip, Encoding.Default))
            {

                // here, we extract every entry, but we could extract conditionally
                // based on entry name, size, date, checkbox status, etc.  
                foreach (ZipEntry e in zip1)
                {
                    e.Extract(toLabelFilePath, ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }

        public static void UnpackTempaltes(string configName, string toDir)
        {
            string toPath = string.Empty;
            if (string.IsNullOrEmpty(toDir))
            {
                toPath = System.IO.Path.Combine(Util.GetUserDataPath() + GlobalStaticDirectoryPath.AOTSProfilePath, configName);
                if (!Directory.Exists(toPath))
                    Directory.CreateDirectory(toPath);
            }
            else
            {
                toPath = toDir;
            }
            using (ZipFile zip1 = ZipFile.Read(Util_DTE.AddIn_SetUpPath + "Data\\Templates.zip", Encoding.Default))
            {

                // here, we extract every entry, but we could extract conditionally
                // based on entry name, size, date, checkbox status, etc.  
                foreach (ZipEntry e in zip1)
                {
                    e.Extract(toPath, ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }

        #endregion
    }
                                                                                                            
    /// <summary>
    /// ObjectTree右键菜单中 “打开新窗口”的显示方式
    /// 如果是MDIParent，则只能用 NewWin
    /// 如果是 UserControl ，则只能用 DockWin
    /// </summary>
    public enum  NewFormDisplayMode
    {
        /// <summary>
        /// 以新窗口的方式显示，MDIParent 内部
        /// </summary>
        MDIParent=0,   
         
        /// <summary>
        /// 以Dock形式显示，UserControl 内部
        /// </summary>
        UserControl
    }
}
